package aos.entity;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;

import aos.exception.AosException;
import aos.log.LogUtils;

public class EventTable {
	// <nodeId, <logicTime, Event> >
	private HashMap<Integer, HashMap<Integer, Event>> events;

	public EventTable(String eventsFile) throws AosException {
		events = new HashMap<Integer, HashMap<Integer, Event>>();
		Scanner cin = null;
		try {
			cin = new Scanner(new FileReader(eventsFile));
		} catch (IOException e) {
			LogUtils.errorLog("eventsFile \"" + eventsFile + "\" load failed");
			LogUtils.errorLog(e.getMessage());
			throw new AosException(e.getMessage(), e);
		}
		cin.next();
		while (cin.hasNext()) {
			Event event = new Event();
			int nodeId = cin.nextInt();
			int logicTime = cin.nextInt();
			String eventType = cin.next();
			event.setNodeId(nodeId);
			event.setLogicTime(logicTime);
			event.setEventType(eventType);
			if (eventType.equalsIgnoreCase("SEND")
					|| eventType.equalsIgnoreCase("TICK")) {
				event.setOption(cin.nextInt());
			}
			HashMap<Integer, Event> map = events.get(event.getNodeId());
			if (map == null) {
				map = new HashMap<Integer, Event>();
			}
			map.put(event.getLogicTime(), event);
			events.put(event.getNodeId(), map);
			LogUtils.debugLog("event: " + event.toString());
		}
		LogUtils.runLog("eventsFile read success");
	}

	public Event getEvent(int nodeId, int logicTime) {
		if (!events.containsKey(nodeId)
				|| !events.get(nodeId).containsKey(logicTime)) {
			return null;
		}
		return events.get(nodeId).get(logicTime);
	}
}
